package com.cskaoyan.servlet;


import com.cskaoyan.bean.KeywordListData;
import com.cskaoyan.bean.KeywordParameter;
import com.cskaoyan.bean.vo.BaseRespVo;
import com.cskaoyan.common.CommonServlet;
import com.cskaoyan.model.MarketKeyword;
import com.cskaoyan.service.KeywordService;
import com.cskaoyan.service.impl.KeywordServiceImpl;

import com.cskaoyan.utils.JacksonUtil;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;

@WebServlet("/admin/keyword/*")
public class AdminKeywordServlrt extends CommonServlet {
    KeywordService keywordService = new KeywordServiceImpl();
    public BaseRespVo list(HttpServletRequest request, HttpServletResponse response){
        Map<String, String[]> parameterMap = request.getParameterMap();
        //将传来的GET数据传入到KeywordParameter对象中
        KeywordParameter keywordParameter = new KeywordParameter();
        try {
            BeanUtils.copyProperties(keywordParameter,parameterMap);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e);
        }
        //得到传来的KeywordListData对象
        KeywordListData keywordListData = keywordService.getKeyword(keywordParameter);

        return BaseRespVo.ok(keywordListData);
    }

    public BaseRespVo create(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String s = request.getReader().readLine();
        Map<String,String> map = JacksonUtil.read(s, Map.class);

        //插入传来的Json数据对象
        MarketKeyword marketKeyword = keywordService.insertNewKeyword(map);
        return BaseRespVo.ok(marketKeyword);
    }

    public BaseRespVo update(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String s = request.getReader().readLine();
        Map<String,String> map = JacksonUtil.read(s, Map.class);
        //更新传来的Json数据对象
        MarketKeyword marketKeyword = keywordService.updateKeyword(map);

        return BaseRespVo.ok(marketKeyword);
    }

    public BaseRespVo delete(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String s = request.getReader().readLine();
        Map<String,String> map = JacksonUtil.read(s, Map.class);

        //删除传来的Json数据对象
        keywordService.deleteKeyword(map);

        return BaseRespVo.ok(null);
    }
}
